<?php
/**
 *
 * @file View.php
 *
 * Class for the different views.
 *
 * This class represents by default the view that is demanded by client.
 * You can change this as follows:
 *
 * @code
 *   $foo = new View('another/file/to/view');
 *   $foo->var = "bar";
 *
 *   echo $foo;
 * @endcode
 *
 * http://code.google.com/p/rpd/wiki/View.php
 *
 * New BSD License
 * \n
 * Copyright (c) 2010 Rpd-Team
 *
 * @namespace  rpd
 * @since      0.0.1
 * @version    0.0.1
 */

class View {

	protected $_file;
	protected $_map = array();

	function __call($func, $args)
	{
		$o = $this->$func;
		return $o($args[0]);
	}

	/**
	 * Get a variable of the View
	 * \code
	 * 	$view = new View();
	 * 	echo $view->foo; // will call $view->_get("foo");
	 * \endcode
	 * If the variable doesn't exists it will lookup the file and include it.
	 * Let's say:
	 *  - app\View\subpage\subpage.php
	 *  - app\View\subpage\foo.php
	 * \code
	 *   // subpage.php:
	 *
	 *   $view = new View();
	 *   echo $view->foo;
	 *   // variable hasn't been set so "app\View\subpage\foo.php" is included
	 * \endcode
	 * @param string $item
	 */
	function __get($item)
	{
		if (!isset($this->_map[$item]))
		{
			$dir  = dirname($this->_file);
			if ($dir != ".")
			{
				$dir .= "/";
			}
			else
			{
				$dir = "";
			}

				$this->_map[$item] = new View($dir . $item);
		}
		return $this->_map[$item];
	}

	function __invoke($in)
	{
		if (is_array($in))
		{
			$this->_map = array_replace(
		               		$this->_map,
		               		$in
			);
		}
		else if ($in instanceof Iterator)
		{
			$r = "";
			foreach ($in as $set)
			{
				$r .= (string) $this->__invoke($set);
			}

			return $r;
		}


		return $this;
	}

	/**
	 * Set variable of the View
	 * \code
	 * 	$view = new View();
	 * 	$view->foo = "bar";	// will call $view->_set("foo", "bar")
	 * \endcode
	 * @param string $item
	 * @param string $value
	 */
	function __set($item, $value)
	{
		$this->_map[$item] = $value;
	}


	/**
	 * Dispatch the choosen file
	 * @return string
	 */
	function __toString()
	{
		global $site;
		// let view generate the output
		if (file_exists("app/View/" . $this->_file . ".php"))
		{
			ob_start();
			include("app/View/" . $this->_file . ".php");
			return ob_get_clean();
		}
		return "";
	}

	/**
	 * Associate file as a View
	 * @param string $file Path to the file without "app/View"
	 */
	function __construct($file = NULL) {

		if ($file === NULL)
		{
			$this->_file = DIR . FILE;
		}
		else
		{
			$this->_file = $file;
		}


		foreach (Registry::get("view/append") as $s)
		{
			if (   $s != ""
			    && file_exists("app/View/" . $this->_file . $s . ".php")
			    )
			{
				$this->_file .= $s;
			}
		}
	}

}

?>